package cn.knet.excel.imp.knetexceltool.service;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.util.Collection;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.LongAdder;

@Service
@Slf4j
public class BindCleanService {

    @Value("${bindclean.dir}")
    private  String dir_wzPath ="";

    @Resource
    private DnsService dnsService;

    public void startCleanBind() throws Exception {
        long stime = System.currentTimeMillis();
        LongAdder okAdder = new LongAdder();
        LongAdder failAdder = new LongAdder();
        log.info(String.format("====starting load domains from dir[%s] in order to clean bind ====",dir_wzPath));
        File srcFile = new File(dir_wzPath);
        if (srcFile.exists()) {
            Collection<File> files = FileUtils.listFiles(srcFile, new String[]{"txt"}, false);
            int fcount = 1;
            ExecutorService exector = Executors.newFixedThreadPool(10);
            for (File file : files) {
                /**
                 * 因为文件太多，使用多线程的方式批量处理
                 */
                exector.submit(new BindCleanThread(file, okAdder, failAdder,dnsService));
                fcount++;
            }

            exector.shutdown();
            //保证任务全部执行完
            while (!exector.awaitTermination(10, TimeUnit.MINUTES)) {
                System.out.println("**** please wait,in importing.... ****");
            }
            log.info(String.format("<<<<所有txt都已经处理完毕 总计清理 total_ok_fail[%s_%s_%s]>>>>", okAdder.sum() + failAdder.sum(), okAdder.sum(), failAdder.sum()));
        } else {
            throw new Exception("你输入的文件路径不存在");
        }
        long etime = System.currentTimeMillis();
        log.info(String.format("====ending load domains from dir[%s] in order to clean bind ====total-time[%s]秒", dir_wzPath, (etime - stime) / 1000d));
    }
}
